package com.sz.ac.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sz.ac.model.constant.Vars;

@Component
public class AccessInterceptor extends HandlerInterceptorAdapter
{
	private static final Logger LOGGER = LoggerFactory.getLogger(AccessInterceptor.class);
	
    @Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelView) throws Exception 
	{
		super.postHandle(request, response, obj, modelView);
	}
    
    @Override
   	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception 
    {
    	boolean preHandleStatus = true;
		HttpSession session = request.getSession();
    	String uri = request.getRequestURI();
    	Object key = session.getAttribute(Vars.LOGINKEY);
    	if(null == key && !uri.contains("/grp"))
    	{
    		String json = "{'errno': 302,'time': '"+System.currentTimeMillis()+"','errmsg': 'redirect login','data': ''}";
    		JSONObject responseJSONObject = JSON.parseObject(json);  
    	    response.setCharacterEncoding("UTF-8");  
    	    response.setContentType("application/json; charset=utf-8");
    		response.getWriter().append(responseJSONObject.toString());
//    		response.sendRedirect("/ac/page/login.html");
    		return false;
    	}
    	return preHandleStatus;
    }
    
}
